import router from './router'
import store from './store'
import NProgress from 'nprogress' // Progress 进度条
import 'nprogress/nprogress.css'// Progress 进度条样式
import Cookies from 'js-cookie'
import { Message } from 'element-ui'
import { getToken } from '@/utils/auth' // 验权
import { validatenull } from "@/utils/validate";

import Layout from '@/views/layout/Layout';
import { mapGetters } from 'vuex'

import { getMenu } from '@/api/login'

/**处理动态路由【开始】**/
const _import = require('@/router/_import_' + process.env.NODE_ENV)//获取组件的方法
var getRouter //用来获取后台拿到的路由

//添加路由
function routerGo(to, next) {
  getRouter = filterAsyncRouter(getRouter) //过滤路由
  router.addRoutes(getRouter) //动态添加路由
	router.options.routes=getRouter;//将路由数据传递给全局变量，做侧边栏菜单渲染工作
  next({ ...to, replace: true })
}
//localStorage 存储数组对象的方法
function saveObjArr(name, data) {
	//console.log(data)
  localStorage.setItem(name, JSON.stringify(data))
}
//localStorage 获取数组对象的方法
function getObjArr(name) {
  return JSON.parse(window.localStorage.getItem(name));
}
//遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap) {
  const accessedRouters = asyncRouterMap.filter(route => {
    if (route.component) {
      if (route.component === 'Layout') {//Layout组件特殊处理
        route.component = Layout
      } else {
        route.component = _import(route.component)
      }
    }
    if (route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children)
    }
    return true
  })
  return accessedRouters
}
/**处理动态路由【结束】**/



const whiteList = ['/login','/wxlogin'] // 不重定向白名单
router.beforeEach((to, from, next) => {
  //console.log("router.beforeEach.getToken()="+getToken())
  NProgress.start();
	//debugger
  if (getToken()) {
   // debugger
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done() // if current page is dashboard will not trigger	afterEach hook, so manually handle it
    } else {

      if (store.getters.roles.length === 0||store.getters.allowMenu.length===0) {
        //console.log("更新用户信息");
        store.dispatch('GetInfo').then(res => { // 拉取用户信息
				//登录失效的情况
        if(res.data.success!=true){
            store.dispatch('FedLogOut').then(() => {
                //Message.error(err || 'Verification failed, please login again')
                next({ path: '/' })
              })
        }else{
					//读取菜单（开始）
					if (!getRouter) {//不加这个判断，路由会陷入死循环
							if (!getObjArr('router')||1==1) {
								//从后端获取路由
								console.log("从后端获取路由")
									console.log(res.data.menus)
									getRouter = res.data.menus//后台拿到路由

									saveObjArr('router', getRouter) //存储路由到localStorage
									routerGo(to, next)//执行路由跳转方法


							} else {//从localStorage拿到了路由
								console.log("从localStorage获取路由")
								getRouter = getObjArr('router')//拿到路由
								routerGo(to, next)
							}

					}
					//读取菜单（结束）

        	next();
        }



        }).catch((err) => {
        	console.log(err);
         // next({ path: '/' })
          store.dispatch('FedLogOut').then(() => {
						getRouter=null;
           // Message.error(err || 'Verification failed, please login again')
            next({ path: '/' })
          })
        })
      } else {
        console.log("不更新用户信息");
        next()
      }

    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
			getRouter=null;
      next(`/login?redirect=${to.path}`) // 否则全部重定向到登录页
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done() // 结束Progress
})




